<?php
namespace app\index\controller;
use app\common\model\ForumNoteCateModel;
use app\common\model\ForumNoteModel;
use app\common\model\ForumNoteCommentModel;
use app\common\model\ForumZanModel;
use app\common\model\ForumCollectModel;
use app\common\model\ForumImgModel;
use app\common\model\CenterModel;

class Forum extends Base
{

    //论坛首页
    public function index()
    {

        //定义分页条数
        $limit = 10;
        $params = request()->param();
//        dd(11,$params);
        $cateid = empty($params['cateid']) ? 0: $params['cateid'];
        $type = empty($params['type']) ? 0: $params['type'];
        $content = empty($params['content']) ? 1: $params['content'];

        if($this->center_info) {
            $center_info = $this->center_info;
            $nowDay = strtotime(date('Ymd'));
            $last_sign_time = strtotime(date('Ymd', $center_info['last_sign_time']));
            if ($nowDay == $last_sign_time) {
                $this->assign('is_signin',0);
            }else{
                $this->assign('is_signin',1);
            }
        }else{
            $this->assign('is_signin',0);
        }

        //获取帖子分类列表
        $cate = new ForumNoteCateModel();
        $where_cate = ['state'=>1];
        $cate_list = $cate->getAllCates($where_cate);
        foreach($cate_list as $k=>$v){
            $cate_arr[$v['id']] = $v['name'];
        }

        //获取置顶帖子列表
        $note = new ForumNoteModel();
        $note_top_list = $note->getTopNoteList();
        $time = time();

        foreach($note_top_list as $k=>$v){
            if( abs($time - strtotime($v['update_time'])) < 60*10 ){
                $note_top_list[$k]['update_time_con'] = "刚刚";
            }else{
                $note_top_list[$k]['update_time_con'] = date( 'Y-m-d H:i', strtotime($v['update_time']) );
            }
        }

        //获取帖子列表
        list($note_list,$note_list_count) = $this->notePage(1,$limit);
//        dd($note_list,$note_list_count);

        //把侧边栏位做成可选择显示
//        $side = $this->side();
//        $this->assign('side',$side);

        $this->assign('cateid',$cateid);
        $this->assign('type',$type);
        $this->assign('content',$content);

        $this->assign('note_top_list', $note_top_list);
        $this->assign('note_list',$note_list);
        $this->assign('note_list_count',$note_list_count);
        $this->assign('limit',$limit);
        $this->assign('cate_list',$cate_list);
//        $this->assign('title','Sea社区');


        return $this->fetch();
    }

    /**
     * 获取分页数据
     * @return mixed
     */
    public function notePage($curr = 1,$limit = 10)
    {
        $params = request()->param();
        //帖子分类筛选
        if( !empty($params['cateid']) ){
            $where_note['a.cate_id'] = $params['cateid'];
            $where_note_count['cate_id'] = $params['cateid'];
        }

        //内容筛选
        $select_type = empty($params['type']) ? 0 : $params['type']; //0综合；1未结；2已结；3精华
        $select_content = empty($params['content']) ? 1 : $params['content'];//1按最新；2按热议；

        if($select_type == 1){
            $where_note['a.is_end'] = 0;
            $where_note_count['is_end'] = 0;
        }elseif($select_type == 2){
            $where_note['a.is_end'] = 1;
            $where_note_count['is_end'] = 1;
        }elseif($select_type == 3){
            $where_note['a.is_good'] = 1;
            $where_note_count['is_good'] = 1;
        }else{
            //do nothing
        }

        if($select_content == 1) {
            $order = "a.update_time desc";
        }else{
            $order = "a.comment_num desc";
        }

        $where_note['a.state'] = 1;
        $where_note['a.is_top'] = ['neq',1];
        $where_note_count['state'] = 1;
        $where_note_count['is_top'] = ['neq',1];

        $curr = empty($params['curr']) ? $curr : $params['curr'];
        $limit = empty($params['limit']) ? $limit : $params['limit'];

        $note = new ForumNoteModel();
//        $list = $note->where($where_note)->limit( ($curr-1)*$limit.','.$limit )->select();
        $list = $note->alias('a')
            ->join('z_forum_note_cate b','a.cate_id=b.id','LEFT')
            ->join('z_center c','a.center_id=c.id','LEFT')
            ->where($where_note)
            ->order($order)
            ->limit( ($curr-1)*$limit.','.$limit )
            ->field('a.id,a.center_id,a.title,a.credit,a.update_time,a.comment_num,a.is_end,a.is_good,a.is_top,b.name,c.username,c.thumb')
            ->select();
        $note_list_count = $note->getNoteCount($where_note_count);

        $time = time();
        foreach($list as $k=>$v){
            if( abs($time - strtotime($v['update_time'])) < 60*10 ){
                $list[$k]['update_time_con'] = "刚刚";
            }else{
                $list[$k]['update_time_con'] = date( 'Y-m-d H:i', strtotime($v['update_time']) );
            }
        }

        if(request()->isPost()){
            echo json_encode($list);
        }else{
            return array($list, $note_list_count);
        }

    }

    /**
     * 帖子详情
     * @return mixed
     */
    public function noteDetail()
    {
        $params = request()->param();
        $note = new ForumNoteModel();
        if( !empty($params['id']) && $info = $note->getOneNote($params) ){
            $comment = new ForumNoteCommentModel();
            $commentList = $comment->getCommentList($params);

            $zanArr = [];
            $zan = new ForumZanModel();
            $zanNum = $zan->zanCount($params['id']);
            if( CID ){
                $zanArr = $zan->getNoteZanList(['note_id'=>$params['id'],'center_id'=>CID]);
            }

            $this->assign('zanNum',$zanNum);
            $this->assign('zanArr',$zanArr);
            $this->assign('note_info',$info);
            $this->assign('commentList',$commentList);
        }else{
            $this->error('帖子不存在');
        }

        return $this->fetch();
    }


    /**
     * @return mixed
     */
    public function setNote(){
        $params = request()->param();
        $note = new ForumNoteModel();

        $res = $note->setNote($params);
        echo json_encode($res);
    }

    /**
     * @return mixed
     */
    public function delNote(){
        $params = request()->param();
        $note = new ForumNoteModel();

        $res = $note->delNote($params);
        echo json_encode($res);
    }

    /**
     * @return mixed
     */
    public function collect(){
        $params = request()->param();
//        dd($params);
        if( !empty($params['note_id']) && !empty($params['type']) && CID ){
            $collect = new ForumCollectModel();
            $params['center_id'] = CID;

            if( $params['type'] == 'add' ){
                $res = $collect->insertCollect($params);
            }elseif( $params['type'] == 'remove' ){
                $res = $collect->delCollect($params);
            }else{
                $res = fmsg(1, '', '数据错误');
            }
        }else{
            $res = fmsg(1, '', '收藏失败');
        }

        echo json_encode($res);
    }

    public function findCollect(){
        $params = request()->param();
        $collect = new ForumCollectModel();
        $res = $collect->findCollect($params);
        if( $res['msg']=='已收藏' ){
            $res['data']['collection'] = true;
        }elseif( $res['msg']=='未收藏' ){
            $res['data']['collection'] = false;
        }
        echo json_encode($res);
    }


    //案列
    public function case1()
    {
        return $this->fetch();
    }

    //新增帖子
    public function addnote()
    {
        if (request()->isPost()) {
            $param = input("post.");
            $note = new ForumNoteModel();
            $flag = $note->insertNote($param);
            if($flag['code'] == 1){
                $this->success($flag['msg'],$flag['data']);
            }else{
                $this->error($flag['msg']);
            }
//            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }else{
            $cate = new ForumNoteCateModel();
            $where = ['state'=>1];
            $cate_list = $cate->getAllCates($where);
            $this->assign('cate_list',$cate_list);
            return $this->fetch();
        }

    }

    //编辑帖子
    public function editnote()
    {
        if (request()->isPost()) {
            $param = input("post.");
            $note = new ForumNoteModel();

            $flag = $note->updateNote($param);
            if($flag['code'] == 1){
                $this->success($flag['msg'],$flag['data']);
            }else{
                $this->error($flag['msg']);
            }
        }else{
            $cate = new ForumNoteCateModel();
            $where = ['state'=>1];
            $cate_list = $cate->getAllCates($where);

            $params = request()->param();
            $note = new ForumNoteModel();
            if(empty($params['id'])){
                $this->error('数据错误');
            }
            $note_info = $note->getOneNote($params);
            $this->assign('cate_list',$cate_list);
            $this->assign('note_info',$note_info);
//            dd($note_info);
            return $this->fetch('addnote');
        }

    }

    /**
     * 上传图片
     */
    public function upload(){
        $file = request()->file('file');
        $params = request()->param();
        if(isset($file)){
            $savePath = ROOT_PATH.'public'.DS.'upload'.DS.'forum/'; //设置图片绝对路径
            if( !is_dir($savePath) ){
                mkdir($savePath ,0777,true);
            }
//            $info = $file->move($savePath);
            $info = $file->validate(['size'=>2*1024*1024,'ext'=>'jpg,png,gif'])->move($savePath);
            if($info){
                // 成功上传后 获取上传信息
//                echo $info->getExtension(); // 输出 jpg
//                echo $info->getSaveName(); // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                $fileName = $info->getFilename();

                $tempPath = DS.'upload'.DS.'forum'.DS.date('Ymd').DS.$fileName;  //保存图片相对路径

//                $forumImg = new ForumImgModel();
//                $forumImg->insertImg();
                $res['status'] = 0;
                $res['url'] = $tempPath;
                $res['msg'] = '成功';

                echo json_encode($res);
            }else{
                // 上传失败获取错误信息
//                echo $file->getError();
                $res['status'] = 1;
                $res['msg'] = '失败';

                echo json_encode($res);
            }
        }

    }


    /**********************************帖子详情detail************************/
    /**
     *点赞
     */
    public function zan(){
        $params = request()->param();  //["ok"] => string(4) "true" ，["id"] => string(1) "1"，，["note_id"] => string(1) "7"

        if(empty($params['id']) || empty($params['note_id']) || !$this->center_info){
            $res['status'] = 1;
            $res['msg'] = '数据错误';
        }else{
            $center_info = $this->center_info;
            $data['comment_id'] = $params['id'];
            $data['center_id'] = $center_info['id'];
            $data['note_id'] = $params['note_id'];

            $zan = new ForumZanModel();
            $zanInfo = $zan->getZanInfo($data);

            if($params['ok'] == 'false') {
                if ($zanInfo) {
                    $res['status'] = 1;
                    $res['msg'] = '已经点赞过了';
                } else {
                    $flag = $zan->insertZan($data);
                    if ($flag['code'] == 1) {
                        $res['status'] = 0;
                        $res['msg'] = '点赞成功';
                    } else {
                        $res['status'] = 1;
                        $res['msg'] = '点赞失败';
                    }
                }
            }else{
                if ($zanInfo && $zan->delZanInfo($data)) {
                    $res['status'] = 0;
                    $res['msg'] = '取消点赞成功';
                }else{
                    $res['status'] = 1;
                    $res['msg'] = '取消点赞失败';
                }
            }

        }
        echo json_encode($res);
    }


    /**
     * 评论回复
     */
    public function reply(){
        $params = request()->param();

        $params['pid'] = empty($params['parent_comment_id']) ? 0 : $params['parent_comment_id'];
        $params['center_id'] = CID;

        $comment = new ForumNoteCommentModel();
        $note = new ForumNoteModel();
//        dd($note->setCommentNum($params['note_id'],'+'));
        if( !empty($params['note_id']) && $note->setCommentNum($params['note_id'],'+')){
            $res = $comment->insertComment($params);
        }else{
            $res = fmsg(1, '', '评论失败1!');
        }
        echo json_encode($res);
    }


    /**
     * 采纳
     */
    public function accept(){
        $params = request()->param();

        if(!empty($params['id'])){
            $comment = new ForumNoteCommentModel();
            $res = $comment->setCommentAccept($params['id']);
        }else{
            $res['status'] = 1;
            $res['msg'] = '数据错误';
        }
        echo json_encode($res);
    }

    /**
     * 获取评论
     */
    public function getComment(){
        $params = request()->param();
        if(!empty($params['id'])){
            $comment = new ForumNoteCommentModel();
            $info = $comment->getOneComment(['id'=>$params['id']]);
            $res['rows'] = $info;
            $res['msg'] = '获取成功';
            $res['status'] = 0;
        }else{
            $res['status'] = 1;
            $res['msg'] = '数据错误';
        }
        echo json_encode($res);
    }

    /**
     * 修改评论
     */
    public function setComment(){
        $params = request()->param();

        $comment = new ForumNoteCommentModel();
        $res = $comment->setComment($params);

        echo json_encode($res);
    }

    /**
     * 删除评论
     */
    public function delComment(){
        $params = request()->param();

        $comment = new ForumNoteCommentModel();
        $note = new ForumNoteModel();
        if( !empty($params['note_id']) && $note->setCommentNum($params['note_id'],'-')){
            $res = $comment->delComment($params);
        }else{
            $res = fmsg(1, '', '删除失败!');
        }


        echo json_encode($res);
    }

    /**
     * 签到
     */
    public function signin(){
        $center_info = $this->center_info;
        $center = new CenterModel();

        if( CID ){
            $where['username'] = $center_info['username'];
            $login_info =  $center->getOneCenter($where);
            $nowDay = strtotime(date('Ymd'));
            $last_sign_time = strtotime(date('Ymd',$login_info['last_sign_time']));

            if($nowDay == $last_sign_time){
                $res['data']['signed'] = true;
                $continue_num = $login_info['continue_sign_num']+1;
            }else{
                $res['data']['signed'] = false;
                if($nowDay == $last_sign_time+86400){
                    $continue_num = $login_info['continue_sign_num']+1;
                }else{
                    $continue_num = 1;
                }
            }
            $res['data']['days'] = $continue_num;
        }
        $res['status'] = 0;
        $res['data']['token'] = 123;
        $res['data']['experience'] = 15;
        echo json_encode($res);
    }

    /**
     * 签到榜
     */
    public function signinTop(){
        $center = new CenterModel();

        $newList = $center->signinNew();
        $fastList = $center->signinFast();
        $topList = $center->signinTop();

        $res['data'][0] = $newList;
        $res['data'][1] = $fastList;
        $res['data'][2] = $topList;
        $res['status'] = 0;
        echo json_encode($res);
    }

    /**
     * 今日签到
     */
    public function todaySignin(){
        $params = request()->param();
        $center = new CenterModel();

        if( CID && $login_info =  $center->getOneCenter(['id'=>CID]) ){
            $nowDay = strtotime(date('Ymd'));
            $last_sign_time = strtotime(date('Ymd',$login_info['last_sign_time']));
            if($nowDay == $last_sign_time){
                $res['status'] = 1;
                $res['msg'] = '今日已签到';
            }else{
                if($nowDay == $last_sign_time+86400){
                    $saveD['continue_sign_num'] = $login_info['continue_sign_num']+1;
                }else{
                    $saveD['continue_sign_num'] = 1;
                }
                $saveD['last_sign_time'] = time();

                if($center->where(['id'=>CID])->update($saveD)){
                    session('center_info',$login_info);
                    $res['status'] = 0;
                    $res['msg'] = '签到成功';
                    $res['data']['signed'] = 1;
                    $res['data']['experience'] = 15;
                    $res['data']['days'] = 2;
                }else{
                    $res['status'] = 1;
                    $res['msg'] = '签到失败';
                }
            }
        }else{
            $res['status'] = 1;
            $res['msg'] = '请登录';
            $res['data'] = [];
        }
        echo json_encode($res);
    }



/********************************侧边栏****开始*******************************/

    /**
     *侧边显示控制（待设计）
     */
    public function side($pageName='note_index'){

    }


    //回帖周榜
    public function noteCommentTop(){
        $noteComment = new ForumNoteCommentModel();
        $data = $noteComment->noteCommentTop();

        $res['status'] = 0;
        $res['data'] = $data;

        echo json_encode($res);
    }

    //本周热议
    public function noteTop(){
        $noteComment = new ForumNoteCommentModel();
        $data = $noteComment->noteTop();

        $res['status'] = 0;
        $res['data'] = $data;

        echo json_encode($res);
    }
    /********************************侧边栏****结束*******************************/



}
